import 'dart:developer' as developer;
import 'package:azring/core/repository/auth_repository.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:azring/entity/sendcode_entity.dart';
import 'package:azring/entity/getinfo_entity.dart';
import '../services/storage_service.dart';
import '../../main.dart';
import '../../pages/profile/ProfileLogic.dart';
import '../../pages/status/status_logic.dart';
import '../../pages/sleep/sleep_logic.dart';
import '../../pages/action/actionLogic.dart';
import '../../pages/insights/InsightsLogic.dart';
import '../../pages/status/daily_events/daily_events_logic.dart';
import '../../services/device_storage_service.dart';
import '../../services/device_sn_manager.dart';
import './ring_controller.dart';

class AuthController extends GetxController {
  static AuthController get to => Get.find();
  final AuthRepository _repository = AuthRepository();

  // final _isLoading = false.obs;
  final _isLoggedIn = false.obs;
  final Rx<GetinfoUser?> _user = Rx<GetinfoUser?>(null);

  // bool get isLoading => _isLoading.value;

  bool get isLoggedIn => _isLoggedIn.value;

  GetinfoUser? get user => _user.value;

  @override
  void onInit() {
    super.onInit();
    checkAuthStatus();
  }

  Future<void> checkAuthStatus() async {
    final token = Get.find<StorageService>().getToken();
    _isLoggedIn.value = token != null;
    if (_isLoggedIn.value) {
      await getUserInfo();
    }
  }

  Future<void> login(
      {required String username,
      String? password,
      String? code,
      String? uuid,
      String loginType = '1'}) async {
    try {
      showLoading();
      await Get.find<StorageService>().clearToken();
      _isLoggedIn.value = false;
      _user.value = null;
      final response = await _repository.login(
        username: username,
        password: password,
        code: code,
        uuid: uuid,
        loginType: loginType,
      );

      if (response.isSuccess && response.data != null) {
        await StorageService.to.setToken(response.data!['token']);
        await StorageService.to.setUserName(username);
        _isLoggedIn.value = true;
        await getUserInfo();
        
        // 初始化核心控制器（登录成功后）
        await initCoreControllers();
        
        Get.offAllNamed('/status');

      } else {
        Toast.show(response.msg);
      }
    } catch (e) {
      // Toast.show('Error', e.toString());
    } finally {
      dismissLoading();
    }
  }

  Future<void> getUserInfo() async {
    try {
      final response = await _repository.getInfo();
      if (response.isSuccess && response.data != null) {
        _user.value = response.data?.user;
      }
    } catch (e) {
      // Toast.show('Error', e.toString());
    }
    return null;
  }

  Future<SendcodeEntity?> sendEmail(String email) async {
    try {
      showLoading();
      final response = await _repository.sendEmail(email, '1');
      if (response.isSuccess) {
        // Toast.show('Success', 'Email sent successfully');
        return response.data!;
      } else {
        Toast.show( 'Email sent failed');
      }
    } catch (e) {
      Toast.show( 'Email sent failed');
    } finally {
      dismissLoading();
    }
    return null;
  }

  Future<void> register({
    required String username,
    required String password,
    required String code,
    required String uuid,
    String userType = '1',
  }) async {
    try {
      showLoading();
      final response = await _repository.register(
        username: username,
        password: password,
        code: code,
        uuid: uuid,
        userType: userType,
        loginType: "1"
      );
        print(response);
      if (response.isSuccess && response.data != null) {
        await StorageService.to.setToken(response.data!);
        // await StorageService.to.setUserName(username);
        _isLoggedIn.value = true;
        await getUserInfo();
        
        // 初始化核心控制器（注册成功后）
        await initCoreControllers();
        Get.offAllNamed('/questionnaire');
      } else {
        Toast.show(response.msg);
      }
    } catch (e) {
      print(e);
      Toast.show('注册失败，请重试$e');
    } finally {
      dismissLoading();
    }
  }

  Future<void> logout() async {
    try {
      showLoading();
      
      // 1. 断开设备连接
      if (Get.isRegistered<RingController>()) {
        try {
          await Get.find<RingController>().disconnectDevice();
        } catch (e) {
          developer.log('断开设备连接失败: $e', name: 'AuthController');
        }
      }
      
      // 2. 清除设备存储数据
      if (Get.isRegistered<DeviceStorageService>()) {
        try {
          await Get.find<DeviceStorageService>().clearAllData();
        } catch (e) {
          developer.log('清除设备存储失败: $e', name: 'AuthController');
        }
      }
      
      // 3. 清除设备 SN 管理器数据
      if (Get.isRegistered<DeviceSnManager>()) {
        try {
          await Get.find<DeviceSnManager>().clearDeviceSn();
        } catch (e) {
          developer.log('清除设备SN失败: $e', name: 'AuthController');
        }
      }
      
      // 4. 清除本地所有用户数据（包括 token、用户名等）
      await Get.find<StorageService>().clearAllUserData();
      
      // 5. 清除内存中的用户信息（包括头像、昵称等）
      _isLoggedIn.value = false;
      _user.value = null;
      
      // 6. 删除业务控制器（保留核心服务）
      _clearBusinessControllers();
      
      // 7. 尝试调用后端登出接口（忽略错误）
      try {
        await _repository.logout();
      } catch (e) {
        // 忽略登出接口错误，因为本地已经清除
      }
      
      // 8. 跳转到登录页
      Get.offAllNamed('/login');
    } catch (e) {
      // 即使出错也要跳转到登录页
      Get.offAllNamed('/login');
    } finally {
      dismissLoading();
    }
  }

  /// 清除业务控制器（保留核心服务如 StorageService、AuthController）
  void _clearBusinessControllers() {
    try {
      // 删除 ProfileLogic
      if (Get.isRegistered<dynamic>(tag: 'ProfileLogic')) {
        Get.delete<dynamic>(tag: 'ProfileLogic', force: true);
      }
      // 尝试通过类型删除
      try {
        Get.delete<ProfileLogic>(force: true);
      } catch (e) {
        // 忽略错误
      }
      
      // 删除其他业务控制器
      try {
        Get.delete<StatusLogic>(force: true);
      } catch (e) {}
      try {
        Get.delete<SleepLogic>(force: true);
      } catch (e) {}
      try {
        Get.delete<ActionLogic>(force: true);
      } catch (e) {}
      try {
        Get.delete<InsightsLogic>(force: true);
      } catch (e) {}
      try {
        Get.delete<DailyEventsLogic>(force: true);
      } catch (e) {}
      
    } catch (e) {
      developer.log('清除业务控制器时出错: $e', name: 'AuthController');
    }
  }
}
